#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"

#define ESP_MAXIMUM_RETRY 10

// WIFI_AUTH_OPEN
// WIFI_AUTH_WEP
// WIFI_AUTH_WPA_PSK
// WIFI_AUTH_WPA2_PSK
// WIFI_AUTH_WPA_WPA2_PSK
// WIFI_AUTH_WPA3_PSK
// WIFI_AUTH_WPA2_WPA3_PSK
// WIFI_AUTH_WAPI_PSK

/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event, but we only care about two events:
 * - we are connected to the AP with an IP
 * - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1

static const char *TAG = "wifi";

static int s_retry_num = 0;

static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
void wifi_start_sta(wifi_config_t *wifi_config);
uint16_t wifi_scan(wifi_ap_record_t ap_info[], uint16_t max_ap);
void wifi_init(void);

static void event_handler(void *arg, esp_event_base_t event_base,
                          int32_t event_id, void *event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
    {
        esp_wifi_connect();
    }
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
    {
        if (s_retry_num < ESP_MAXIMUM_RETRY)
        {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGI(TAG, "retry to connect to the AP");
        }
        else
        {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }
        ESP_LOGI(TAG, "connect to the AP fail");
    }
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
    {
        ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
        ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

void wifi_start_sta(wifi_config_t *wifi_config)
{
    ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
    s_wifi_event_group = xEventGroupCreate();

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));
    // wifi_config_t wifi_config = {
    //     .sta = {
    //         .ssid = ESP_WIFI_SSID,
    //         .password = ESP_WIFI_PASS,
    //         .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD,
    //         .sae_pwe_h2e = ESP_WIFI_SAE_MODE,
    //     },
    // };
    wifi_config->sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "wifi_init_sta finished.");

    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
                                           WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
                                           pdFALSE,
                                           pdFALSE,
                                           portMAX_DELAY);

    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if (bits & WIFI_CONNECTED_BIT){
        ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
                 wifi_config->sta.ssid, wifi_config->sta.password);
    }else if (bits & WIFI_FAIL_BIT){
        ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
                 wifi_config->sta.ssid, wifi_config->sta.password);
    }else{
        ESP_LOGE(TAG, "UNEXPECTED EVENT");
    }
}

/* Initialize Wi-Fi as sta and set scan method */
uint16_t wifi_scan(wifi_ap_record_t ap_info[], uint16_t max_ap)
{
    ESP_LOGI(TAG, "WIFI SCANNING");
    uint16_t ap_count = 0;

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());
    esp_wifi_scan_start(NULL, true);
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&max_ap, ap_info));
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));
    ESP_ERROR_CHECK(esp_wifi_stop());
    return ap_count;
}

void wifi_init(void)
{
    // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // 
        ESP_ERROR_CHECK(nvs_flash_erase()); 
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
}

// Connect to specified router hotspots and whether to enable scanning hotspots
void wifi_connect_config(char* SSID, char* PASSWORD, int* SCANMAXNUM)
{
    if(SSID == NULL || PASSWORD == NULL){
        if(SSID == NULL){
            ESP_LOGI(TAG, "ssid is NULL");
        }else{
            ESP_LOGI(TAG, "password is NULL");
        }
    }

    // Set hotspot name and password
    wifi_sta_config_t wifi_config;
    memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
    strcpy((char*)&wifi_config.ssid, SSID);
    strcpy((char*)&wifi_config.password, PASSWORD);

    // WiFi configuration initialization
    wifi_init();

    // Configure the maximum number of hotspots to scan around
    if(SCANMAXNUM != NULL){
        wifi_ap_record_t* ap_info = (wifi_ap_record_t*)malloc(sizeof(wifi_ap_record_t)*(*SCANMAXNUM));
        wifi_scan(ap_info, *SCANMAXNUM);
    }

    // connect WiFi
    wifi_start_sta((wifi_config_t*)&wifi_config);
}
